﻿var mysql = require('mysql');
var qs = require('querystring');/*将字符串与json串的转换*/
var configDB = require('./configDB.js');
var logger = require('../util/log.js');
exports.init = function(){
	var client = mysql.createConnection(configDB.getConfigDB());
	client.connect();

	var userinfo_flag = true;
	var note_flag = true;
	//判断数据库是否存在，不存在则新建
	client.query("create database if not exists `mbf`",function(err,results,fields){
		if(err){
			logger.logger('normal').info("初始化数据库mbf失败："+JSON.stringify(err));
		}		
	});
	try{
		client.query('use information_schema');
		var sql = "SELECT * FROM TABLES WHERE TABLES.TABLE_SCHEMA='mbf'";
		client.query(sql,function(err,results,fields){
		//查询information_schema.tables,查看表是否存在
		for(var i=0;i<results.length;i++){
			var row = results[i];
			if(row.TABLE_NAME === 'note'){
				note_flag = false;
			}
			if(row.TABLE_NAME === 'userinfo'){
				userinfo_flag = false;
			}
		}
		//判断note表是否存在，不存在则从新生成
		if(note_flag){
			logger.logger('normal').info("开始初始化数据表note。");
			var notesql = "CREATE TABLE `note` (`myid` int(11) NOT NULL auto_increment, `userid` varchar(50) default NULL, "+
				"`type` varchar(10) default NULL,`datetime` datetime default NULL,`content` varchar(1000) default NULL,"+
				"`isDelete` int(11) default '0', PRIMARY KEY  (`myid`)) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;";
			client.query('use mbf');
			client.query(notesql,function(err,results,fields){
				if(err){
					logger.logger('normal').info("初始化数据表note失败。");
				}else{
					logger.logger('normal').info("初始化数据表note成功。");
				}
			});
		}
		//判断userinfo表是否存在，不存在则从新生成
		if(userinfo_flag){
			logger.logger('normal').info("开始初始化数据表userinfo。");
			var userinfosql = "CREATE TABLE `userinfo` ("+
			"`userid` varchar(200) NOT NULL,"+
			"`username` varchar(200) default NULL,"+
			"`password` varchar(200) default NULL,"+
			"`sex` varchar(10) default NULL,"+
			"`birthday` varchar(100) default NULL,"+
			"`phoneNum` varchar(100) default NULL,"+
			"`email` varchar(100) default NULL,"+
			"PRIMARY KEY  (`userid`)"+
			") ENGINE=InnoDB DEFAULT CHARSET=utf8;";
			client.query('use mbf');
			client.query(userinfosql,function(err,results,fields){
				if(err){
					logger.logger('normal').info("初始化数据表userinfo失败。");
				}else{
					logger.logger('normal').info("初始化数据表userinfo成功。");
				}
			});
		}
		
		});
	}catch(e){
		logger.logger('normal').info("数据库查询出错，错误信息："+err.message+"  "+e.message);				
	}finally{
		if(client!==undefined&&client===""){
			client.end();
		}
	}
}